<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('变更类型')" prop="changeItem">
            <el-select v-model="form.changeItem" :placeholder="$t('变更类型')" @change="changeItemChange">
              <el-option
                v-for="dict in changeItemOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('变更日期')" prop="transferDate">
            <DatePicker
              v-model="form.transferDate"
              :placeholder="$t('变更日期')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t(itemName) + $t('人')" prop="transferor">
            <fund-lp-select
              v-model="form.transferor"
              :fund-id="form.fundId"
              @change="lpChange($event, 'transferor')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t(itemName) + $t('认缴') + $t('金额单位')" prop="transferSubscription">
            <Money v-model="form.transferSubscription" unit="w" :placeholder="$t(itemName) + $t('认缴')" @change="transferSubscriptionChange">
              <template slot="append">
                <span v-if="containPaidInAmount && containPaidInAmount !== 0" style="color: #F56C6C;">{{ $t('其中包含实缴金额') }} {{ moneyFormat(containPaidInAmount, 'w') }} </span>
              </template>
            </Money>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t(itemName) + $t('实缴') + $t('金额单位')" prop="transferPaidIn">
            <Money v-model="form.transferPaidIn" unit="w" :placeholder="$t(itemName) + $t('实缴')" @change="transferPaidInChange" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.changeItem === 'FEZR'" :span="12">
          <el-form-item :label="$t('受让人来源')" prop="assigneeSource">
            <el-select v-model="form.assigneeSource" :placeholder="$t('受让人来源')" @change="assigneeSourceChange">
              <el-option
                v-for="dict in assigneeSourceOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.assigneeSource === 'WBKH'" :span="12">
          <el-form-item :label="$t('受让人属性')" prop="assigneeProperty">
            <el-select v-model="form.assigneeProperty" :placeholder="$t('受让人属性')" @change="assigneePropertyChange">
              <el-option
                v-for="(item, index) in assigneePropertyOptions"
                :key="index"
                :label="$t(item.dictLabel)"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.changeItem === 'FEZR'" :span="12">
          <el-form-item :label="$t('受让人')" prop="assignee">
            <fund-lp-select
              v-if="form.assigneeSource === 'DQJJ'"
              v-model="form.assignee"
              :fund-id="form.fundId"
              @change="lpChange($event,'assignee')"
            />
            <el-select v-else v-model="form.assignee" :placeholder="$t('受让人')" filterable @change="lpChange($event,'assignee')">
              <el-option
                v-for="lp in lpOptions"
                :key="lp.id"
                :label="lp.name"
                :value="lp.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowTransferorInfo" :span="12">
          <el-divider content-position="center"><span style="color: #409EFF">{{ $t('当前{itemName}人', { itemName: itemName }) }} - {{ $t('认缴金额') }} : {{ moneyFormat(subscribedAmount, 'w') + $t('金额单位') }}</span></el-divider>
        </el-col>
        <el-col v-if="isShowTransferorInfo" :span="12">
          <el-divider content-position="center"><span style="color: #409EFF">{{ $t('当前{itemName}人', { itemName: itemName }) }} - {{ $t('实缴总金额') }} : {{ moneyFormat(paidInTotalAmount, 'w') + $t('金额单位') }}</span></el-divider>
        </el-col>
      </el-row>
      <!-- 附件列表 -->
      <FileTable has-permi="fund:transfer" :list.sync="form.fileList" data-type="fund_share_transfer" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>
    <div v-if="!form.id" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn has-permi="fund:transfer" />
    </div>
  </div>
</template>

<script>
    import { saveFundShareTransfer, getFundShareTransfer } from '@/api/fund/transfer/fundShareTransfer'
    import { changeNameByType, findInvestByFundId } from '@/api/fund/investor/fundInvestor'
    import { getFundInvestor } from '@/api/fund/investor/fundInvestor'
    import FundLpSelect from '@/components/Select/fundLpSelect'
    export default {
      components: { FundLpSelect },
      data() {
            return {
                // 变更项字典
                changeItemOptions: [], // 受让人来源字典
              // 受让人属性字典
              assigneePropertyOptions: [],
                assigneeSourceOptions: [], // 表单参数
              // 受让人
              lpOptions: [],
              // 转让人
              transferorOptions: [],
              // 当前转让人认缴金额
              subscribedAmount: undefined,
              // 当前转让人实缴总金额
              paidInTotalAmount: undefined,
              // 认缴金额所包含实缴金额
              containPaidInAmount: 0,
              // 是否展示当前转让人信息
              isShowTransferorInfo: false,
              // 认缴实缴根据变更项的改变而改变名称
              itemName: '转让',
              // 是否隐藏其它按钮
              otherBtnHide: false,
              fundId: this.$route.query.id,
                form: {},
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  changeItem: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], transferDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], transferor: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], assigneeSource: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], assigneeProperty: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], assignee: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ] }
            }
        },
        created() {
          this.getDicts('change_item').then(response => {
              this.changeItemOptions = response.data
          })
          this.getDicts('assignee_property').then(response => {
              this.assigneeSourceOptions = response.data
          })
          // 客户类型
          this.getDicts('lp_type').then(response => {
            this.assigneePropertyOptions = this.assigneePropertyOptions.concat(response.data)
          })
          // 主体类型
          this.getDicts('main_body_type').then(response => {
            this.assigneePropertyOptions = this.assigneePropertyOptions.concat(response.data)
          })
          findInvestByFundId(this.fundId).then(response => {
            this.transferorOptions = response.data.map((item) => {
              return { id: item.id, name: item.userName }
            })
          })
        },
      methods: {
            // 初始化数据
            init(data) {
              this.loading = true
              this.isShowTransferorInfo = false
                if (data != null && data.id !== undefined) {
                    getFundShareTransfer(data.id).then(response => {
                        this.form = response.data
                      // 去掉份额转让 '份额'文本
                      this.itemName = this.changeItemOptions.find((item) => {
                        return item.dictValue === this.form.changeItem
                      })
                      if (this.itemName) {
                        this.itemName = this.itemName.dictLabel.replace('份额', '')
                      }
                        // 加载受让人列表
                        changeNameByType(this.form.assigneeProperty).then(response => {
                          this.lpOptions = response.data
                          this.loading = false
                        })
                    })
                } else {
                    this.reset()
                    this.assigneeSourceChange(this.form.assigneeSource)
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                fundId: this.fundId,
                changeItem: 'FEZR',
                transferDate: undefined,
                transferor: undefined,
                transferSubscription: 0,
                transferPaidIn: 0,
                assigneeSource: 'DQJJ',
                assigneeProperty: undefined,
                assignee: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                  fileList: []
                }
                this.resetForm('form')
              this.itemName = '转让'
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                      // 验证是否有认缴/实缴变更 都没有变更不可以添加
                      if (this.form.transferSubscription === 0 && this.form.transferPaidIn === 0) {
                        this.$message({
                          showClose: true,
                          message: this.$t('当前无认缴/实缴变更,无法保存!'),
                          type: 'warning'
                        })
                        return
                      }
                      // 计算 剩余认缴
                      let subscriptionAmount = 0
                      // 计算 剩余实缴
                      let paidInAmount = 0
                      // 变更项 != 增资 进行认缴/实缴验证
                        if (this.form.changeItem !== 'ZZ') {
                          subscriptionAmount = this.subscribedAmount - this.form.transferSubscription
                          paidInAmount = this.paidInTotalAmount - this.form.transferPaidIn
                          // 验证变更认缴金额是否超过当前转让人认缴金额
                          if (this.form.transferSubscription > this.subscribedAmount) {
                            this.$message({
                              showClose: true,
                              message: this.$t('当前{itemName}认缴金额已超过当前LP持有份额!', { itemName: this.itemName }),
                              type: 'warning'
                            })
                            return
                          }
                          // 验证变更实缴金额是否超过当前转让人实缴金额
                          if (this.form.transferPaidIn > this.paidInTotalAmount) {
                            this.$message({
                              showClose: true,
                              message: this.$t('当前{itemName}实缴金额已超过当前LP持有份额!', { itemName: this.itemName }),
                              type: 'warning'
                            })
                            return
                          }
                          // 验证 变更认缴金额是否超过当前转让人可变更认缴金额
                          const amount = (this.subscribedAmount + this.form.transferSubscription) - (this.form.transferPaidIn + this.paidInTotalAmount)
                          if (amount < 0 || paidInAmount > subscriptionAmount) {
                            this.$alert(this.$t('当前LP认缴金额为') + ': <span style="color: #F56C6C;"> ' + this.moneyFormat(this.subscribedAmount, 'w') + '</span> ' + this.$t('金额单位') + ',' +
                              this.$t('实缴金额') + ': <span style="color: #F56C6C;"> ' + this.moneyFormat(this.paidInTotalAmount, 'w') + '</span> ' + this.$t('金额单位') + ',' +
                              this.$t('目前可变更金额为') + ': <span style="color: #F56C6C;"> ' + this.moneyFormat((this.subscribedAmount - this.paidInTotalAmount) + this.form.transferPaidIn, 'w') + '</span> ' + this.$t('金额单位') + ',' +
                              this.$t('当前{itemName}认缴金额已超过可变更金额!', { itemName: this.itemName }), this.$t('系统提示'), {
                              confirmButtonText: this.$t('确定'),
                              type: 'warning',
                              dangerouslyUseHTMLString: true
                            })
                            return
                          }
                        } else {
                          subscriptionAmount = this.subscribedAmount + this.form.transferSubscription
                          paidInAmount = this.paidInTotalAmount + this.form.transferPaidIn
                        }
                        // 获取当前转让人名称
                      const lpName = this.transferorOptions.find((item) => {
                        return item.id === this.form.transferor
                      }).name
                      // 保存前展示份额转让信息
                      this.$confirm(this.$t('当前{itemName}人为', { itemName: this.itemName }) + ': </br><span style="color: #F56C6C;"> ' + lpName + ' </span>' +
                        '</br>' + this.$t('此次') + this.itemName + ':<br/>' + this.$t('认缴金额') + ': <span style="color: #F56C6C;"> ' + this.moneyFormat(this.form.transferSubscription, 'w') + this.$t('金额单位') + ' </span> ' +
                        // this.$t('万') +
                        '</br>' +
                        this.$t('实缴金额') + ': <span style="color: #F56C6C;"> ' + this.moneyFormat(this.form.transferPaidIn, 'w') + this.$t('金额单位') + ' </span> ' +
                        // this.$t('万') +
                        '</br>' +
                        this.itemName + '后:</br>认缴金额剩余:  <span style="color: #F56C6C;"> ' + this.moneyFormat(subscriptionAmount, 'w') + this.$t('金额单位') + ' </span></br>' +
                        this.$t('实缴金额剩余') + ':  <span style="color: #F56C6C;"> ' + this.moneyFormat(paidInAmount, 'w') + this.$t('金额单位') + ' </span></br>' +
                        this.$t('表单保存后无法修改,请确认表单信息!'), this.$t('系统提示'), {
                        confirmButtonText: this.$t('确定'),
                        cancelButtonText: this.$t('取消'),
                        type: 'warning',
                        dangerouslyUseHTMLString: true
                      }).then(() => {
                         this.loading = true
                        saveFundShareTransfer(this.form).then(response => {
                          if (response.code === 200) {
                            this.msgSuccess(this.$t('保存成功'))
                            this.closeForm()
                          } else {
                            this.msgError(response.msg)
                          }
                          this.loading = false
                        }).catch(() => {
                          this.loading = false
                        })
                      })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 受让人来源change事件
          assigneeSourceChange(val) {
              // 切换受让人事件项时 清空受让人和受让人属性
              if (val === 'DQJJ') {
                this.form.assignee = undefined
              } else {
                this.form.assignee = undefined
                this.form.assigneeProperty = undefined
                this.lpOptions = []
              }
          },
        // 受让人属性change事件
          assigneePropertyChange(val) {
              // 选择受让人属性时 加载选择的受让人列表
            this.form.assignee = undefined
            changeNameByType(val).then(response => {
              this.lpOptions = response.data
            })
          },
        // 变更项事件
          changeItemChange(val) {
              // 去掉份额转让 '份额'文本
              this.itemName = this.changeItemOptions.find((item) => {
                return item.dictValue === val
              }).dictLabel.replace('份额', '')
            this.form.transferSubscription = 0
            this.form.transferPaidIn = 0
            this.containPaidInAmount = 0
             if (val !== 'FEZR') {
               this.form.assigneeSource = undefined
               this.assigneeSourceChange('DQJJ')
               this.form.assigneeProperty = undefined
               this.form.assignee = undefined
            }
          },
          lpChange(val, property) {
            this.$nextTick(() => {
              if (this.form.transferor === this.form.assignee) {
                this.$message({
                  showClose: true,
                  message: this.itemName + this.$t('人和受让人不能是同一出资人'),
                  type: 'info'
                })
                if (property === 'transferor') {
                  this.form.transferor = undefined
                  this.isShowTransferorInfo = false
                } else {
                  this.form.assignee = undefined
                }
                return
              }
              if (property === 'transferor') {
                getFundInvestor(val).then(response => {
                  this.subscribedAmount = response.data.subscribedAmount ? response.data.subscribedAmount : 0
                  this.paidInTotalAmount = response.data.accumulatedPaidMount ? response.data.accumulatedPaidMount : 0
                  this.isShowTransferorInfo = true
                })
              }
            })
          },
        // 认缴金额改变触发
        transferSubscriptionChange(val) {
              if (this.form.transferor) {
                if (this.form.changeItem !== 'ZZ') {
                  if (val < this.form.transferPaidIn) {
                    this.$nextTick(() => {
                      this.form.transferSubscription += this.form.transferPaidIn
                    })
                    this.$message({
                      type: 'info',
                      message: this.$t('已自动累加认缴金额') + this.moneyFormat(this.form.transferPaidIn, 'w') + this.$t('金额单位')
                    })
                  }
                } else {
                  const amount = (val + this.subscribedAmount) - (this.form.transferPaidIn + this.paidInTotalAmount)
                  if (amount < 0) {
                    this.$nextTick(() => {
                      this.form.transferSubscription += Math.abs(amount)
                    })
                    this.$message({
                      type: 'info',
                      message: this.$t('已自动累加认缴金额') + this.moneyFormat(Math.abs(amount), 'w') + this.$t('金额单位')
                    })
                  }
                }
              } else {
                this.$nextTick(() => {
                  this.form.transferSubscription = undefined
                })
                this.$message({
                  showClose: true,
                  message: this.$t('请先选择{itemName}人', { itemName: this.itemName }),
                  type: 'warning'
                })
              }
          },
        // 实缴金额改变触发
          transferPaidInChange(val) {
            if (this.form.transferor) {
              if (this.form.changeItem !== 'ZZ') {
                if (val > this.form.transferSubscription) {
                  this.form.transferSubscription = val
                }
                this.containPaidInAmount = val
              } else {
                const amount = (this.form.transferSubscription + this.subscribedAmount) - (val + this.paidInTotalAmount)
                if (amount < 0) {
                  this.$confirm(this.$t('当前{itemName}人总实缴金额已超过总认缴金额', { itemName: this.itemName }) + ' <span style="color: #F56C6C;">' + this.moneyFormat(Math.abs(amount), 'w') + '</span> ' + this.$t('金额单位') + ',' +
                    this.$t('是否将超出金额添加到{itemName}认缴中', { itemName: this.itemName }), this.$t('系统提示'), {
                    confirmButtonText: this.$t('确定'),
                    cancelButtonText: this.$t('取消'),
                    type: 'info',
                    dangerouslyUseHTMLString: true
                  }).then(() => {
                    this.$nextTick(() => {
                      this.form.transferSubscription += Math.abs(amount)
                      this.containPaidInAmount += Math.abs(amount)
                    })
                  }).catch(() => {
                    this.form.transferPaidIn = 0
                    this.$message({
                      type: 'info',
                      message: this.$t('取消添加{itemName}认缴金额,重新输入', { itemName: this.itemName })
                    })
                  })
                } else {
                  this.containPaidInAmount = val
                }
              }
            } else {
              this.$message({
                showClose: true,
                message: this.$t('请先选择{itemName}人', { itemName: this.itemName }),
                type: 'warning'
              })
              this.$nextTick(() => {
                this.form.transferPaidIn = 0
              })
            }
          }
        }
    }
</script>
<style scoped>

</style>
